﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Routing;
using SW.Lite.BLL.Master;
using SW.Lite.Infrastructure.Helpers;
using SW.Lite.Model.Master;

namespace SW.Lite.Core.Authority
{
    /// <summary>
    ///     Class BaseController.
    /// </summary>
    public class BaseController : Controller
    {
        /// <summary>
        ///     The page size
        /// </summary>
        public const int PageSize = 20;

        /// <summary>
        ///     The _admin
        /// </summary>
        private AdminModel _admin = new AdminModel { Id = 1, UserName = "Administrator", NickName = "超级管理员", Password = "61BUYlShX376o5wSv0LJAeR0olM=", PasswordSalt = "MBQLVr", Face = "/Upload/Face/2015/L8I79D.jpg", LoginCount = 138, LastLoginTime = DateTime.Parse("2015-05-12 10:57:30.570"), LastLoginIP = "1.202.56.198" };

        private ICollection<RoleModel> _roles;

        /// <summary>
        ///     Gets the admin.
        /// </summary>
        /// <value>The admin.</value>
        public AdminModel CurrentAdmin
        {
            get
            {
                if (_admin != null)
                    return _admin;

                var adminId = SessionHelper.Instance.GetSession<int>("AdminID");
                if (adminId == 0)
                    return null;

                _admin = Admin.Single(adminId);
                return _admin;
            }
        }

        /// <summary>
        ///     Gets the roles.
        /// </summary>
        /// <value>The roles.</value>
        public ICollection<RoleModel> Roles
        {
            get
            {
                if (CurrentAdmin == null)
                    return null;
                return _roles ?? (_roles = Role.GetRolesByAdminId(CurrentAdmin.Id));
            }
        }

        /// <summary>
        ///     Validates this instance.
        /// </summary>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public virtual bool Validate()
        {
            return CurrentAdmin != null;
        }

        /// <summary>
        ///     Initializes data that might not be available when the constructor is called.
        /// </summary>
        /// <param name="requestContext">The HTTP context and route data.</param>
        protected override void Initialize(RequestContext requestContext)
        {
            base.Initialize(requestContext);
            if (!Validate())
                Response.Redirect(Url.Action("Index", "Login") + "?ReturnUrl=" + Server.UrlEncode(Request.RawUrl));
        }
    }
}